#!/bin/bash

# ----------------------------
# 一键升级组件
# ----------------------------

set -e

TOKEN='Bearer eyJraWQiOiJ1YWEta2V5LTIyMDIxNiIsImFsZyI6IlJTMjU2In0.eyJleHAiOjE3NDM0MDE2NjcsImlkIjoic3VwZXJfYWRtaW4iLCJ1c2VyX25hbWUiOiJzdXBlcl9hZG1pbiIsInRlbmFudF9pZCI6InN1cGVyX2FkbWluIiwiYXV0aG9yaXRpZXMiOiJzdXBlcl9hZG1pbiJ9.ct8V54wwlCpbSlZ4flyqyNINEn5ZXSCXymFKns3nIGDzA-2icuzp4gdVZY7gQFKQLLvGL3jN0OkbFTt8ETzCWGskgQipnMWbtPe0Dm0jlMohjPh7kZp1opSUDpwv55oC_shakm9a5rCdGqsTvuPF6yq53cBDmhAA3oo2HEmbUHZin417PbpzF8RFQ6BboKu8J2tigShOhdbrj7PSvmZ42pxDCzuWqjNk2lr3kNtZqRiRvDWnt3l1oXF4raVHtmS0UnIeJv7vpGwICVvFwopAjesA17K52ujP1DfFMcWtZEafzxr3TEdjy4uljpFRysz_AuTC_6LnrD9CGITTIzD4Zg'
BASE_URL="10.50.26.195"

echo '1. 上传组件包'
response=$(curl http://${BASE_URL}:29010/api/v1/component/upload/unzip -X POST -H "Authorization: ${TOKEN}" -F "file=@/Users/mojito/Downloads/data-platform-V3.0R25C00.zip")
data=$(echo "$response" | jq -r '.data')
echo "组件包上传结果=${data}"

echo '2. 获取组件id'
response=$(curl -s -X POST http://${BASE_URL}:29010/api/v1/component/upload/task/dataplatform-compose.yml -H "Authorization: ${TOKEN}" -H "Content-Type: application/json" -d "{\"uploadId\":\"${data}\"}")
uploadId=$(echo "$response" | jq -r '.data.uploadId')
echo "组件id=${uploadId}"

echo '3. 更新组件'
response=$(curl http://${BASE_URL}:29010/api/v1/component/update -X POST -H "Authorization: ${TOKEN}" -d "{\"uploadId\":\"${uploadId}\"}")
uploadData=$(echo "$response" | jq -r '.data')
echo "更新组件结果=${uploadData}"

FIELD_NAME="success"               # 要检查的 JSON 字段（例如 "success" 或 "status"）
EXPECTED_VALUE="true"              # 期望的字段值
POLL_INTERVAL=2                    # 轮询间隔（秒）
MAX_RETRIES=100                     # 最大重试次数（超时 = POLL_INTERVAL * MAX_RETRIES）

echo "4. 轮训查询更新结果"
retry=0

while [ $retry -lt $MAX_RETRIES ]; do
    # 调用接口并获取 JSON 响应
    response=$(curl -s -X GET http://${BASE_URL}:29010/api/v1/tasks/info/${uploadData} -H "Authorization: ${TOKEN}")

    # 检查 curl 是否成功
    if [ $? -ne 0 ]; then
        echo "❌ 请求失败！请检查网络或接口地址"
        exit 1
    fi

    # 使用 jq 解析目标字段
    field_value=$(echo "$response" | jq -r ".data.finalStatus")

    # 检查字段值是否符合预期
    if [ "$field_value" != "RUNNING" ]; then
        echo "✅ 条件满足！字段 [$FIELD_NAME] = [$field_value]"
        exit 0
    else
        echo "⏳ 尝试 $((retry + 1))/$MAX_RETRIES: 当前 [$FIELD_NAME] = [$field_value]，等待 $POLL_INTERVAL 秒后重试..."
        sleep $POLL_INTERVAL
        ((retry++))
    fi
done

echo "❌ 超时：在 ${MAX_RETRIES} 次重试后未检测到 [$FIELD_NAME] = [$EXPECTED_VALUE]"
exit 1